<template>
  <HeadContainer :title="$t('title.uploadIdentity')" @back="backToPrev">
    <div class="gap-col-16">
      <div class="text-white font-size-14 font-style-normal font-weight-500 line-height-140">
        {{ $t('info.beCreator.upload.1') }}
      </div>
      <div>
        <input
          type="file"
          capture="camera"
          accept="image/jpg, image/jpeg, image/png, image/gif"
          hidden
          ref="identityCapture"
          @change="(e) => (identityPhoto = e.target.files[0])"
        />
        <div for="" class="text-white font-size-12 font-style-normal font-weight-400 line-height-120">
          1. {{ $t('label.picture.identity') }}
        </div>
        <div v-if="!identityPhoto" class="take-picture" :class="{ error: !!validateIdentity.error }">
          <div
            class="text-white font-size-14 font-style-normal font-weight-500 line-height-140 d-flex justify-center align-center"
            @click="takePicture(BECOME_CREATOR_PHOTO_TYPE.IDENTITY)"
          >
            <Icon size="14" class="mr-3" name="camera"></Icon>
            {{ $t('info.picture.identity') }}
          </div>
        </div>
        <div v-else>
          <div class="card gap-col-16 mt-2">
            <div class="picture bg-primary">
              <v-img :src="srcIdentity" class="picture" cover></v-img>
            </div>
            <div class="divider"></div>
            <div
              class="text-white font-size-14 font-style-normal font-weight-500 line-height-140 d-flex justify-center align-center"
              @click="takePicture(BECOME_CREATOR_PHOTO_TYPE.IDENTITY)"
            >
              <Icon size="14" class="mr-3" name="camera"></Icon>
              {{ $t('info.picture.recapture') }}
            </div>
          </div>
        </div>
        <div v-if="validateIdentity.error" class="err-msg font-size-12 font-weight-400 line-height-120 text-primary-x">
          {{ validateIdentity.error }}
        </div>
      </div>
      <div>
        <input
          type="file"
          capture="camera"
          accept="image/jpg, image/jpeg, image/png, image/gif"
          hidden
          ref="faceCapture"
          @change="(e) => (facePhoto = e.target.files[0])"
        />
        <div class="text-white font-size-12 font-style-normal font-weight-400 line-height-120">
          2. {{ $t('label.picture.face') }}
        </div>
        <div v-if="!facePhoto" class="take-picture" :class="{ error: !!validateFace.error }">
          <div
            class="text-white font-size-14 font-style-normal font-weight-500 line-height-140 d-flex justify-center align-center"
            @click="takePicture(BECOME_CREATOR_PHOTO_TYPE.FACE)"
          >
            <Icon size="14" class="mr-3" name="camera"></Icon>
            {{ $t('info.picture.face') }}
          </div>
        </div>
        <div v-else>
          <div class="card gap-col-16 mt-2">
            <div class="picture bg-primary">
              <v-img :src="srcFace" class="picture" cover></v-img>
            </div>
            <div class="divider"></div>
            <div
              class="text-white font-size-14 font-style-normal font-weight-500 line-height-140 d-flex justify-center align-center"
              @click="takePicture(BECOME_CREATOR_PHOTO_TYPE.FACE)"
            >
              <Icon size="14" class="mr-3" name="camera"></Icon>
              {{ $t('info.picture.recapture') }}
            </div>
          </div>
        </div>
        <div v-if="validateIdentity.error" class="err-msg font-size-12 font-weight-400 line-height-120 text-primary-x">
          {{ validateIdentity.error }}
        </div>
      </div>
      <div class="d-flex flex-col gap-col-8">
        <div class="text-white font-size-14 font-style-normal font-weight-500 line-height-140">
          {{ $t('info.beCreator.upload.2') }}
        </div>
        <div class="d-flex flex-row gap-row-5">
          <div class="text-white font-size-12 font-style-normal line-height-140">
            {{ $t('info.beCreator.upload.label') }}
          </div>
          <div class="text-subtitle font-size-12 font-style-normal line-height-140">
            {{ $t('info.beCreator.upload.span') }}
          </div>
        </div>
        <div class="grid-options gap-row-8 gap-col-8">
          <div v-for="option in sexOrientationOptions" :key="`sex-option-${option.value}`">
            <Tag
              :label="option.label"
              :value="option.value"
              :selected="option.value === sexOrientation"
              primary-selected
              narrow-padding
              @click="sexOrientation = option.value"
            ></Tag>
          </div>
        </div>
      </div>
      <v-divider></v-divider>
      <BlockButton :label="$t('label.sendRequest')" :is-gradient="false" @click="openConfirmDialog"></BlockButton>
    </div>
  </HeadContainer>
</template>
<script setup>
import { computed, reactive, ref } from 'vue'
import { VImg } from 'vuetify/components'
import { storeToRefs } from 'pinia'
import { useAppStore } from '@/store/app'
import { useBecomeCreatorDataStore } from '@/store/become-creator-data'
import { useBecomeCreatorRouteStore } from '@/store/become-creator-route'
import { useDialogStore } from '@/store/dialog'
import { usePopupDialogStore } from '@/store/popup-dialog'
import { $t } from '@/i18n'
import { parseError, useYup } from '@/plugins/yup'
import { transBlobToUrl } from '@/utils/transform.js'
import BlockButton from '@/components/button/BlockButton.vue'
import Tag from '@/components/common/Tag.vue'
import HeadContainer from '@/components/layout/HeadContainer.vue'
import { BECOME_CREATOR_PHOTO_TYPE, BECOME_CREATOR_ROUTES, INTERESTED_IN, POPUP_DIALOG_TYPE } from '@/constant'
import API from '@/http'
import uploadImage from '@/http/upload/uploadImage'

const sexOrientation = ref(INTERESTED_IN.STRAIGHT)
const sexOrientationOptions = [
  { label: $t('interestedIn.straight'), value: INTERESTED_IN.STRAIGHT },
  { label: $t('interestedIn.gay'), value: INTERESTED_IN.GAY },
  { label: $t('interestedIn.lesbian'), value: INTERESTED_IN.LESBIAN },
  { label: $t('interestedIn.trans'), value: INTERESTED_IN.TRANS },
]

const identityCapture = ref(null)
const faceCapture = ref(null)

const { isMobile } = storeToRefs(useAppStore())

const routeStore = useBecomeCreatorRouteStore()
const { to, back } = routeStore

const dataStore = useBecomeCreatorDataStore()
const { identityPhoto, facePhoto, photoType, profile } = storeToRefs(dataStore)

const takePicture = (type) => {
  if (isMobile.value) {
    type === BECOME_CREATOR_PHOTO_TYPE.IDENTITY ? identityCapture.value.click() : faceCapture.value.click()
    return
  }

  photoType.value = type
  to(BECOME_CREATOR_ROUTES.PHOTO_CAPTURE)
}

// v1.2 可能會用到
// const toNext = () => {
//   if (!identityPhoto.value || !facePhoto.value) return
//   to(BECOME_CREATOR_ROUTES.IDENTITY_PROFILE)
// }

const { mixed } = useYup()
const schemaFace = mixed().required({ key: 'yup.mixed.facePhoto' })
const schemaIdentity = mixed().required({ key: 'yup.mixed.identityPhoto' })
const validateFace = reactive({
  error: '',
  check: false,
})
const validateIdentity = reactive({
  error: '',
  check: false,
})

const { $popupDialog } = usePopupDialogStore()
const emit = defineEmits(['backToMine'])

const dialogStore = useDialogStore()
const { loadingMask } = storeToRefs(dialogStore)

const openConfirmDialog = async () => {
  schemaIdentity
    .validate(identityPhoto.value)
    .then(() => {
      validateIdentity.error = ''
      validateIdentity.check = true
    })
    .catch((e) => {
      validateIdentity.error = parseError(e)
      validateIdentity.check = false
    })

  schemaFace
    .validate(facePhoto.value)
    .then(() => {
      validateFace.error = ''
      validateFace.check = true
    })
    .catch((e) => {
      validateFace.error = parseError(e)
      validateFace.check = false
    })

  if (!validateFace.check || !validateIdentity.check) return

  $popupDialog(POPUP_DIALOG_TYPE.CONFIRM, {
    title: $t('title.reconfirm'),
    content: $t('content.confirmSendRequest'),
    confirm: async () => {
      try {
        loadingMask.value = true
        profile.value.certificateFront = await uploadImage(identityPhoto.value, () => {})
        profile.value.certificateBack = await uploadImage(facePhoto.value, () => {})

        const data = {
          idtype: profile.value.identityType,
          certificate_front: profile.value.certificateFront,
          certificate_back: profile.value.certificateBack,
          area: profile.value.country,
          interested_type: sexOrientation.value,
        }

        profile.value.socialLinks.instagram && (data.link_instagram = profile.value.socialLinks.instagram)
        profile.value.socialLinks.twitter && (data.link_twitter = profile.value.socialLinks.twitter)
        profile.value.socialLinks.other && (data.link_other = profile.value.socialLinks.other)

        const applyResult = await API.Creator.apply({ data })
        if (!applyResult.appid) throw new Error('Apply failed')
      } catch (e) {
        console.error(e)
      } finally {
        loadingMask.value = false
      }
    },
    cancel: () => {},
    confirmText: $t('common.continue'),
    cancelText: $t('common.cancel'),
    showClose: false,
  })
    .next(POPUP_DIALOG_TYPE.ALERT, {
      title: $t('title.reconfirm'),
      content: $t('content.sendRequestSuccess'),
      confirmText: $t('common.confirm'),
      confirm: async () => {
        dataStore.$reset()
        routeStore.reset()
        emit('backToMine')
      },
      showClose: false,
    })
    .open()
}

const srcIdentity = computed(() => {
  return identityPhoto.value ? transBlobToUrl(identityPhoto.value) : null
})
const srcFace = computed(() => {
  return facePhoto.value ? transBlobToUrl(facePhoto.value) : null
})

const backToPrev = () => {
  profile.value.certificateFront = ''
  profile.value.certificateBack = ''
  identityPhoto.value = null
  facePhoto.value = null
  back()
}
</script>
<style scoped lang="scss">
.take-picture {
  margin-top: 0.21rem;
  display: flex;
  height: 2.5rem;
  padding: 1rem;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  border-radius: 0.625rem;
  background: var(--bg-dialog, #333546);
}

.card {
  display: flex;
  padding: 1rem;
  flex-direction: column;
  align-items: center;
  align-self: stretch;

  border-radius: 0.625rem;
  background: var(--bg-dialog, #333546);
}

.picture {
  width: 16.875rem;
  height: 10.625rem;
  border-radius: 0.625rem;
}

.divider {
  width: 100%;
  height: 1px;

  background: rgba(255, 255, 255, 0.27);
}

.error {
  border: 0.0625rem solid rgb(var(--v-theme-primary-x));
  background: linear-gradient(0deg, rgba(235, 0, 27, 0.1) 0%, rgba(235, 0, 27, 0.1) 100%),
    rgb(var(--v-theme-background));
}

.grid-options {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
}
</style>
